package com.daquexian.flexiblerichtextview.span;

import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.style.DynamicDrawableSpan;

import com.daquexian.flexiblerichtextview.MyConfige;
import com.daquexian.flexiblerichtextview.R;

public class WavyLineSpan extends DynamicDrawableSpan {

    private BitmapDrawable mRedWavy;
    private int mWidth;
    private int mBmpHeight;

    public WavyLineSpan(Resources resources) {
        super(DynamicDrawableSpan.ALIGN_BASELINE);
        mRedWavy = new BitmapDrawable(resources, BitmapFactory.decodeResource(resources, R.drawable.wavy_line_4));
        mBmpHeight = mRedWavy.getIntrinsicHeight();
        mRedWavy.setTileModeX(Shader.TileMode.REPEAT);
    }

    @Override
    public Drawable getDrawable() {
        return mRedWavy;
    }

    @Override
    public int getSize(Paint paint, CharSequence text,
                       int start, int end,
                       Paint.FontMetricsInt fm) {
        mWidth = (int) paint.measureText(text, start, end);
        return mWidth;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text,
                     int start, int end, float x,
                     int top, int y, int bottom, Paint paint) {

        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        float height1 = fontMetrics.descent - fontMetrics.ascent;
        float height2 = fontMetrics.bottom - fontMetrics.top;

        mRedWavy.setBounds((int)x, 0, (int)(mWidth + x), mBmpHeight);
        canvas.save();
        //canvas.translate(0, bottom-mBmpHeight + 5 - MyConfige.lineSpacingExtra);
        canvas.translate(0, top + height2 - mBmpHeight + 12);
        mRedWavy.draw(canvas);
        canvas.restore();
        canvas.drawText(text.subSequence(start, end).toString(), x, y, paint);
    }
}
